from forest.server.api.util import fixup_path
fixup_path()

import webapp2
from sqlalchemy.orm import scoped_session, sessionmaker

class WSGIApplication(webapp2.WSGIApplication):
    dbsession = None
    def __init__(self, *args, **kwargs):
        engine = kwargs.pop('engine')
        super(WSGIApplication, self).__init__(*args, **kwargs)
        self.router.set_dispatcher(self.__class__.custom_dispatcher)
        WSGIApplication.dbsession = scoped_session(sessionmaker(bind=engine))

    @staticmethod
    def custom_dispatcher(router, request, response):
        try:
            rv = router.default_dispatcher(request, response)
            if isinstance(rv, basestring):
                rv = webapp2.Response(rv)
            elif isinstance(rv, tuple):
                rv = webapp2.Response(*rv)
            return rv
        except:
           WSGIApplication.dbsession.rollback()
           raise
        finally:
           WSGIApplication.dbsession.commit()
            # If the above alone doesn't work, uncomment 
            # the following line:
            #web.ctx.orm.expunge_all() 
        
    def route(self, *args, **kwargs):
        def wrapper(func):
            self.router.add(webapp2.Route(handler=func, *args, **kwargs))
            return func

        return wrapper
